package com.jml.service;

import com.alibaba.fastjson.JSONObject;
import com.jml.config.JmlCloudClientConfig;
import com.jml.constant.ConfigMd5;
import com.jml.utils.HttpClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;

import java.util.HashMap;

public class ConfigClientService implements EnvironmentAware {

    private StandardEnvironment environment;

    @Autowired
    private JmlCloudClientConfig jmlCloudClientConfig;

    /**
     * 从云端读取配置文件
     */
    public JSONObject getConfig() {
        //从配置文件中得到客户端的名字
        String applicationName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(applicationName)) {
            return null;
        }
        HashMap<String, String> mapParam = new HashMap<>();
        mapParam.put("name", applicationName);
        //http调用服务端,得到服务端对的地址获取配置文件
        String serverConfigUrl = jmlCloudClientConfig.getServerConfigUrl();
        JSONObject jsonObject = HttpClientUtils.httpGet(serverConfigUrl + "/getConfig", mapParam);
        Integer code = jsonObject.getInteger("code");
        if (code != 200) {
            return null;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        ConfigMd5.setMd5(data.getString("md5"));
        return data;
    }

    /**
     * 通过服务名字去比较MD5，判断文件是否进行了更改
     *
     * @return
     */
    public JSONObject md5Comparison() {
        String applicationName = environment.getProperty("spring.application.name");
        if (StringUtils.isEmpty(applicationName)) {
            return null;
        }
        HashMap<String, String> mapParam = new HashMap<>();
        mapParam.put("name", applicationName);
        mapParam.put("md5", ConfigMd5.getMd5());
        JSONObject result = HttpClientUtils.httpGet(jmlCloudClientConfig.getServerConfigUrl() + "md5Comparison", mapParam);
        return result;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (StandardEnvironment) environment;
    }
}
